//
//  CertPolicies.m
//  TestProject
//
//  Created by 武侠 on 2022/2/17.
//  Copyright © 2022 zhulong. All rights reserved.
//

#import "CertPolicies.h"
#import "CertItemLength.h"
#import "CertTLV.h"

@implementation CertPolicies

/*
30 3F(63):
    30 3D(61):
        06 08(08): 60 81 1C 86 EF 2A 01 02  (2.16.156.112554.1.2)
        30 31(49):
            30 2F(47):
                06 08(08): 2B 06 01 05 05 07 02 01 (1.3.6.1.5.5.7.2.1)
                           (http://www.cfca.com.cn/us/us-15.htm)
                16 23(35): 68 74 74 70 3A 2F 2F 77 77 77 2E 63 66 63 61 2E 63 6F 6D 2E 63 6E 2F 75 73 2F 75 73 2D 31 35 2E 68 74 6D
 */
- (void)loadCertData {
    char *data = (char *)self.data.bytes;
    int end = (int)self.data.length;
    uint8_t type = data[0];         // 获取类型
    int i = 0;
    
    while (type == 0x30 || type == 0x31) {
        CertItemLength *length = [[CertItemLength alloc] initWithData:data index:i+1];
        i += 1 + length.lenLen;
        if (i >= end) {
            return;
        }
        type = data[i];
    }
    
    // 解析：策略ID
    if (type != 0x06) {
        return;
    }
    CertItemLength *length = [[CertItemLength alloc] initWithData:data index:i+1];
    self.policyId = [CertTLV value:data begin:i];
    
    // 判断是否有 策略数组数据
    i += 1 + length.lenLen + length.len;
    if (i >= end) {
        return;
    }
    
    // 解析：策略数组
    type = data[i];
    if (type != 0x30) {
        return;
    }
    // 计算外层数组的长度信息
    CertItemLength *alength = [[CertItemLength alloc] initWithData:data index:i+1];
    i += 1 + alength.lenLen;        // 偏移外层数组长度
    
    NSMutableArray<CertOID *> *array = [NSMutableArray array];
    while (i < end) {
        length = [[CertItemLength alloc] initWithData:data index:i+1];
        NSData *oidData = [NSData dataWithBytes:data+i length:i+1+length.lenLen+length.len];
        if ([CertOID isValid:oidData] == NO) {
            break;
        }
        [array addObject:[[CertOID alloc] initWithData:oidData]];
        i += 1 + length.lenLen + length.len;
    }
    self.policyQualifiers = array;
}

- (NSString *)description {
    NSString *dPolicyId = [NSString stringWithFormat:@"{\n\tpolicyId(策略ID) : %@", self.policyId];
    NSMutableString *dQualifiers = [NSMutableString string];
    for (int i = 0; i < self.policyQualifiers.count; i++) {
        [dQualifiers appendFormat:@"\t\t[%d]: %@(%@)=%@\n", i, self.policyQualifiers[i].oid, self.policyQualifiers[i].oidDesc, self.policyQualifiers[i].value];
    }
    if (dQualifiers.length > 0) {
        [dQualifiers deleteCharactersInRange:NSMakeRange(dQualifiers.length-1, 1)];
        return [NSString stringWithFormat:@"%@\n\tpolicyQualifiers(策略数组) : [\n%@\n\t]\n}", dPolicyId, dQualifiers];
    }
    return [NSString stringWithFormat:@"%@\n}", dPolicyId];
}

@end
